<template>
  <view ref="barChart" class="histogram-per" :style="{ ...customStyle }"></view>
</template>

<script setup>
import { onMounted, ref, watch, reactive } from "vue";
import echarts from "@/echarts/index.js";
let props = defineProps({
  value: {
    type: [Number],
    default: 0,
  },
  customStyle: {
    type: [String,Object],
    default: () => {
      return {};
    },
  },
  max: {
    type: [Number,String],
    default: 10,
  },
});
let barChart = ref(null);
let preS = ref(0);
let barChartInstance = ref(null);
let barChartOption = reactive({
  xAxis: {
    type: "category",
    data: ["柱子名称"],
    show: false,
  },
  yAxis: {
    show: false,
    type: "value",
    max: props.max,
  },
  series: [
    {
      type: "bar",
      data: [((props.max * (props.value * 100)) / 10000).toFixed(1)], // 将百分比值作为柱子的高度
      showBackground: true,
      itemStyle: {
        normal: {
          color: "green", // 黄色
        },
      },
      label: {
        show: true,
        formatter: () => {
          return props.value + "%";
        }, // 在标签中显示百分比
        fontSize: 8,
      },
    },
  ],
});
onMounted(() => {
  barChartInstance.value = echarts.init(barChart.value?.$el);
  barChartInstance.value.setOption(barChartOption);
});

watch(
  () => props.value,
  (newVal, oldVal) => {
    barChartOption.series[0].data = [
      ((props.max * (newVal * 100)) / 10000).toFixed(1),
    ];
    barChartOption.series[0].label.formatter = () => {
      return newVal + "%";
    };
    barChartInstance.value.setOption(barChartOption);
  }
);
</script>

<style scoped lang="scss">
.histogram-per {
  width: 100rpx;
  height: 160rpx;
}
</style>
